package com.xjj.servicejob.controller.admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.xjj.entity.*;
import com.xjj.servicejob.controller.api.JobSubmitController;
import com.xjj.servicejob.feign.KlassFeignClient;
import com.xjj.servicejob.service.JobService;
import com.xjj.servicejob.service.JobSubmitService;
import com.xjj.servicejob.vo.*;
import com.xjj.util.utils.JwtUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author sjy
 * @create 2022-10-20 11:24
 * 作业的控制器
 */
@RestController
@RequestMapping("/job/admin/job")
public class JobController {
    @Autowired
    private JobService jobService;

    @Autowired
    private KlassFeignClient klassFeignClient;

    @Autowired
    private JobSubmitService jobSubmitService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发布作业
     *
     * @param job
     * @return
     */
    @PostMapping("add")
    public ResponseEntity add(@RequestBody Job job, HttpServletRequest request) throws JsonProcessingException {
        Manager manager = getManager(request.getHeader("token"));
        job.setManagerId(manager.getId());
        Klass klass = new Klass();
        klass.setId(job.getKlassId());
        klassFeignClient.addJobNumById(klass);
        Integer jobId = jobService.add(job);
        ResponseEntity responseEntity = klassFeignClient.getAllStudentsByKlassId(job.getKlassId());
        Object o = responseEntity.getData();
        String s = JSON.toJSONString(o);
        List students = JSONObject.parseObject(s, List.class);
        InitJobSubmitVo initJobSubmitVo = new InitJobSubmitVo();
        initJobSubmitVo.setStudent(students);
        initJobSubmitVo.setJobId(jobId);
        rabbitTemplate.convertAndSend("exchangeTopic", "initJobSubmit", initJobSubmitVo);
        return ResponseEntity.SUCCESS("ok", "成功发布作业");
    }

    /**
     * 修改作业
     *
     * @param job
     * @return
     */
    @PostMapping("update")
    public ResponseEntity update(@RequestBody Job job) {
        //判断是否修改图片
        if (job.getJobPhotos() != null && job.getJobPhotos().size() != 0) {
            job.getJobPhotos().forEach(img -> {
                img.setRelationalId(job.getId());
            });
        }
        jobService.updateJobById(job);
        return ResponseEntity.SUCCESS("ok", "成功修改作业");
    }

    /**
     * 删除作业
     *
     * @param id
     * @return
     */
    @GetMapping("delete/{id}")
    public ResponseEntity delete(@PathVariable Integer id) {
        //TODO 减小班级的作业数（增加分布式事务）
        jobService.deleteById(id);
        return ResponseEntity.SUCCESS("ok", "成功删除作业");
    }

    /**
     * 多条件分页查询作业
     *
     * @param jobVo
     * @return
     */
    @PostMapping("list")
    public ResponseEntity<JobResultVo> getPageBean(@RequestBody JobVo jobVo, HttpServletRequest request) throws JsonProcessingException {
        Manager manager = getManager(request.getHeader("token"));
        //存入job中
        jobVo.getJob().setManagerId(manager.getId());
        JobResultVo jobResultVo = new JobResultVo();
        PageBean<Job> pageBean = new PageBean<>();
        pageBean = jobService.getByPage(jobVo, 2);
        List<Job> jobs = new ArrayList<>();
        List<Job> data = pageBean.getData();
        for (int i = 0; i < data.size(); i++) {
            Job job = data.get(i);
            ResponseEntity responseEntity = klassFeignClient.getKlassById(job.getKlassId());
            Object o = responseEntity.getData();
            String s = JSON.toJSONString(o);
            Klass klass = JSONObject.parseObject(s, Klass.class);
            job.setKlass(klass);
            jobs.add(job);
        }
        pageBean.setData(jobs);
        jobResultVo.setPageBean(pageBean);
        return ResponseEntity.SUCCESS("ok", jobResultVo);
    }

    /**
     * 获取当前作业的详情
     *
     * @param id
     * @return
     */
    @GetMapping("detail/{id}")
    public ResponseEntity<Job> detail(@PathVariable Integer id) {
        //TODO 远程调用接口，获取当前老师的信息和班级信息
        Job job = jobService.detail(id);
        return ResponseEntity.SUCCESS("ok", job);
    }

    /**
     * 获取提交作业的作业详情
     *
     * @param id
     * @return
     */
    @GetMapping("submitDetail/{id}")
    public ResponseEntity<Job> submitDetail(@PathVariable Integer id) {
        //TODO 远程调用接口，获取当前老师的信息和班级信息
        Job job = jobService.detail(id);
        return ResponseEntity.SUCCESS("ok", job);
    }

    /**
     * 获取单个学生提交的作业
     *
     * @param jobSubmitId
     * @return
     */
    @GetMapping("studentJob")
    public ResponseEntity<JobSubmitDetailResultVo> studentJob(@PathVariable Integer jobSubmitId) {
        JobSubmit jobSubmit = jobSubmitService.getById(jobSubmitId);
        Integer jobId = jobSubmit.getJobId();
        Job job = jobService.detail(jobId);
        JobSubmitDetailResultVo jobSubmitDetailResultVo = new JobSubmitDetailResultVo();
        jobSubmitDetailResultVo.setJob(job);
        jobSubmitDetailResultVo.setJobSubmit(jobSubmit);
        return ResponseEntity.SUCCESS("ok", jobSubmitDetailResultVo);
    }

    /**
     * 批改作业
     *
     * @param jobSubmit
     * @return
     */
    @PostMapping("correct")
    public ResponseEntity<String> studentJob(@RequestBody JobSubmit jobSubmit) {
        jobSubmit.setStatus("b");
        jobSubmitService.correctJob(jobSubmit);
        return ResponseEntity.SUCCESS("ok", "成功批改作业");
    }

    /**
     * 查询其所教授的班级
     *
     * @param request
     * @return
     */
    @GetMapping("getTeachClass")
    public ResponseEntity<List> getTeachClass(HttpServletRequest request) throws JsonProcessingException {
        Manager token = getManager(request.getHeader("token"));
        ResponseEntity responseEntity = klassFeignClient.getKlassByManagerId(token.getId());
        Object o = responseEntity.getData();
        String s = JSON.toJSONString(o);
        List klass = JSONObject.parseObject(s, List.class);
        return ResponseEntity.SUCCESS("ok", klass);
    }

    /**
     * 根据作业id查询所有提交的作业
     *
     * @param jobSubmitCheckVo
     * @return
     */
    @PostMapping("getJobSubmit")
    public ResponseEntity<PageBean<JobSubmit>> getJobSubmit(@RequestBody JobSubmitCheckVo jobSubmitCheckVo) {
        PageBean<JobSubmit> pageBean = jobSubmitService.getAllSubmittedJobSubmit(jobSubmitCheckVo, 2);
        List<JobSubmit> allSubmittedJobSubmit = pageBean.getData();
        for (int i = 0; i < allSubmittedJobSubmit.size(); i++) {
            JobSubmit jobSubmit = allSubmittedJobSubmit.get(i);
            Integer studentId = jobSubmit.getStudentId();
            ResponseEntity responseEntity = klassFeignClient.getStudentById(studentId);
            Object o = responseEntity.getData();
            String s = JSON.toJSONString(o);
            Student student = JSONObject.parseObject(s, Student.class);
            jobSubmit.setStudent(student);
        }
        pageBean.setData(allSubmittedJobSubmit);
        return ResponseEntity.SUCCESS("ok", pageBean);
    }

    /**
     * 根据id查询作业的详情
     *
     * @param id
     * @return
     */
    @GetMapping("detailJobSubMit/{id}")
    public ResponseEntity<JobSubmitDetailResultVo> detailJobSubMit(@PathVariable Integer id) {
        JobSubmit jobSubmit = jobSubmitService.getById(id);
        Integer studentId = jobSubmit.getStudentId();
        ResponseEntity responseEntity = klassFeignClient.getStudentById(studentId);
        Object o = responseEntity.getData();
        String s = JSON.toJSONString(o);
        Student student = JSONObject.parseObject(s, Student.class);
        jobSubmit.setStudent(student);
        Job job = jobService.detail(jobSubmit.getJobId());
        JobSubmitDetailResultVo jobSubmitResultVo = new JobSubmitDetailResultVo();
        jobSubmitResultVo.setJobSubmit(jobSubmit);
        jobSubmitResultVo.setJob(job);
        return ResponseEntity.SUCCESS("ok", jobSubmitResultVo);
    }

    /**
     * 根据id修改作业的状态
     *
     * @param id
     * @return
     */
    @PostMapping("updateJobStatus/{id}")
    public ResponseEntity<String> updateJobStatus(@PathVariable Integer id) {
        Job job = new Job();
        job.setId(id);
        job.setStatus("d");
        jobService.updateJobById(job);
        return ResponseEntity.SUCCESS("ok", "修改成功");
    }

    /**
     * 根据token获取解析出来的mananger
     *
     * @param token
     * @return
     * @throws JsonProcessingException
     */
    private Manager getManager(String token) throws JsonProcessingException {
        System.out.println(token);
        //解析出来Manager
        Manager manager = JwtUtil.getManager(token);
        System.out.println("manager" + manager);
        return manager;
    }
}
